<template>
  <div class="contract-container">
    <el-card class="contract-header" :body-style="{ position: 'relative' }">
      <el-form
        :model="queryForm"
        ref="queryFormRef"
        :inline="true"
        label-width="80px"
        class="basic-search-form"
      >
        <el-form-item label="关键词">
          <el-input
            v-model="queryForm.keywords"
            placeholder="请输入合同编号/名称/客户"
            clearable
            @keyup.enter="handleSearch"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="合同类别">
          <el-select
            v-model="queryForm.cate_id"
            placeholder="请选择类别"
            clearable
            style="width: 220px"
          >
            <el-option
              v-for="item in contractCategories"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签约人">
          <el-select
            v-model="queryForm.sign_name"
            placeholder="请输入签约人姓名搜索"
            clearable
            filterable
            remote
            :remote-method="searchSignUsers"
            :loading="signUserLoading"
            style="width: 220px"
          >
            <el-option
              v-for="item in signUserOptions"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="search-buttons">
            <div class="left-buttons">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button @click="toggleAdvancedSearch">
                {{ isAdvancedSearch ? '收起高级' : '高级搜索' }}
                <el-icon class="el-icon--right">
                  <arrow-down v-if="!isAdvancedSearch" />
                  <arrow-up v-else />
                </el-icon>
              </el-button>
            </div>
            <div class="right-buttons">
              <el-button type="success" @click="handleAdd">新增合同</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <!-- 高级搜索面板 -->
      <div v-show="isAdvancedSearch" class="advanced-search-panel">
        <div class="panel-header">
          <div class="panel-title">
            <el-icon><search /></el-icon>
            <span>高级搜索条件</span>
          </div>
          <el-button type="text" @click="closeAdvancedSearch">
            <el-icon>
              <Close />
            </el-icon>
          </el-button>
        </div>
        <el-form
          :model="advancedForm"
          :inline="true"
          label-width="90px"
          class="advanced-search-form"
        >
          <el-form-item label="签约时间" class="form-item">
            <el-date-picker
              v-model="advancedForm.signTimeRange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="合同金额" class="form-item" data-field="amount">
            <div class="amount-input-container">
              <el-input-number
                v-model="advancedForm.min_amount"
                placeholder="最小金额"
                :controls="true"
                :min="0"
                :precision="2"
                :step="100"
                clearable
              />
              <span class="mx-2">至</span>
              <el-input-number
                v-model="advancedForm.max_amount"
                placeholder="最大金额"
                :controls="true"
                :min="0"
                :precision="2"
                :step="100"
                clearable
              />
            </div>
          </el-form-item>

          <el-form-item label="到账金额" class="form-item" data-field="cost2">
            <div class="amount-input-container">
              <el-input-number
                v-model="advancedForm.min_cost2"
                placeholder="最小金额"
                :controls="true"
                :min="0"
                :precision="2"
                :step="100"
                clearable
              />
              <span class="mx-2">至</span>
              <el-input-number
                v-model="advancedForm.max_cost2"
                placeholder="最大金额"
                :controls="true"
                :min="0"
                :precision="2"
                :step="100"
                clearable
              />
            </div>
          </el-form-item>

          <el-form-item label="款项结清" class="form-item">
            <el-select
              v-model="advancedForm.is_cleared"
              placeholder="请选择"
              clearable
              style="width: 220px"
            >
              <el-option :value="1" label="已结清"></el-option>
              <el-option :value="0" label="未结清"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="后期费用" class="form-item">
            <el-select
              v-model="advancedForm.has_cost3"
              placeholder="请选择"
              clearable
              style="width: 220px"
            >
              <el-option :value="1" label="有后期费用"></el-option>
              <el-option :value="0" label="无后期费用"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="是否到期" class="form-item">
            <el-select
              v-model="advancedForm.is_expired"
              placeholder="请选择"
              clearable
              style="width: 220px"
            >
              <el-option :value="1" label="已到期"></el-option>
              <el-option :value="0" label="未到期"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item class="form-item action-buttons" data-field="actions">
            <div class="advanced-buttons">
              <el-button @click="handleReset">重置</el-button>
              <el-button @click="closeAdvancedSearch">取消</el-button>
              <el-button type="primary" @click="handleAdvancedSearch">应用筛选</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="contract-content">
      <!-- 表格工具栏 -->
      <div class="table-toolbar"></div>

      <!-- 使用 Element Plus 原生表格组件替换 BaseTable -->
      <el-table
        :data="contractList"
        :loading="loading"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        @row-click="handleView"
      >
        <el-table-column prop="id" label="ID" width="70" align="center" show-overflow-tooltip />
        <el-table-column prop="code" label="合同编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="name" label="合同名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="customer" label="客户名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="sign_name" label="签约人" width="90" show-overflow-tooltip />
        <el-table-column
          prop="cate_name"
          label="合同类别"
          width="100"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column label="合同金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-cell">¥{{ formatAmount(row.cost) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到账金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-cell">¥{{ formatAmount((row as ContractItem).cost2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="cost3"
          label="后期费用"
          width="120"
          show-overflow-tooltip
          align="right"
        />
        <el-table-column
          prop="sign_time_formatted"
          label="签约时间"
          width="110"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="end_time_formatted"
          label="到期时间"
          width="110"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column label="剩余天数" width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span :class="row.delay < 0 ? 'delay-expired' : 'delay-normal'">
              {{ row.delay }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click.stop="handleView(row)">查看</el-button>
            <el-dropdown @command="handleCommand" @click.stop>
              <el-button size="small" type="default">
                更多
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'edit', row: row }">编辑</el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'stop', row: row }"
                    :disabled="row.stop_status === 1 || row.void_status === 1"
                  >
                    中止合同
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'void', row: row }"
                    :disabled="row.stop_status === 1 || row.void_status === 1"
                  >
                    作废合同
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <BasePagination
          v-model:model-value="queryForm.page"
          v-model:page-size="queryForm.limit"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 合同详情抽屉 -->
    <GlobalDrawer
      v-model="detailDrawerVisible"
      title="合同详情"
      size="80%"
      :show-footer-buttons="false"
    >
      <div class="drawer-content">
        <SaleContractView
          :contract-id="currentDetailContractId"
          :key="'contract-view-' + currentDetailContractId"
        />
      </div>
    </GlobalDrawer>

    <!-- 新增合同抽屉 -->
    <GlobalDrawer
      v-model="addDrawerVisible"
      title="新增合同"
      size="80%"
      @confirm="handleConfirmAdd"
    >
      <div class="drawer-content">
        <SaleContractAdd ref="contractAddRef" @submit="handleAddSubmit" @cancel="closeAddDrawer" />
      </div>
    </GlobalDrawer>

    <!-- 编辑合同抽屉 -->
    <GlobalDrawer
      v-model="editDrawerVisible"
      title="编辑合同"
      size="80%"
      @confirm="submitEditForm"
      @open="handleEditDrawerOpen"
    >
      <div class="drawer-content">
        <SaleContractEdit
          ref="contractEditRef"
          :contract-id="currentEditContractId"
          @submit="handleEditSubmit"
          @cancel="closeEditDrawer"
        />
      </div>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown, ArrowUp, Close, Search } from '@element-plus/icons-vue'
  import { BasePagination } from '@/components/base'
  import { GlobalDrawer } from '@/components/common'
  import SaleContractView from './SaleContractView.vue'
  import SaleContractAdd from './SaleContractAdd.vue'
  import SaleContractEdit from './SaleContractEdit.vue'
  import request from '@/utils/request'
import { contractApi } from '@/api/contract'
import { formatDate } from '@/utils/format'
import type { ContractCategory } from '@/types/contract'
import type { ContractItem } from '@/types/index'
import type { ApiResponse } from '@/types/index'

  // 管理员用户接口
  interface AdminUser {
    id: number
    name: string
    [key: string]: any
  }

  // 合同分类缓存键
  const CONTRACT_CATEGORIES_CACHE_KEY = 'CONTRACT_CATEGORIES'

  // 管理员用户缓存键
  const ADMIN_USERS_CACHE_KEY = 'ADMIN_USERS'

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 10,
    keywords: '',
    cate_id: '',
    sign_name: '', // 只保留签约人姓名搜索字段
  })

  // 高级搜索表单
  const advancedForm = reactive({
    signTimeRange: [] as string[],
    min_amount: null as number | null,
    max_amount: null as number | null,
    min_cost2: null as number | null, // 最小到账金额
    max_cost2: null as number | null, // 最大到账金额
    is_cleared: null as number | null, // 款项结清：1已结清，0未结清，null全部
    has_cost3: null as number | null, // 是否有后期费用：1有，0无，null全部
    is_expired: null as number | null, // 是否到期：1已到期，0未到期，null全部
  })

  // 高级搜索面板显示状态
  const isAdvancedSearch = ref(false)

  // 合同分类列表
  const contractCategories = ref<any[]>([])

  // 数据相关
  const contractList = ref<ContractItem[]>([])
  const total = ref(0)
  const loading = ref(false)

  // 签约人搜索相关
  const signUserOptions = ref<any[]>([])
  const signUserLoading = ref(false)

  // 管理员用户列表
  const adminUsers = ref<AdminUser[]>([])

  // 抽屉相关
  const detailDrawerVisible = ref(false)
  const currentDetailContractId = ref('')
  const addDrawerVisible = ref(false)
  const contractAddRef = ref()
  const editDrawerVisible = ref(false)
  const currentEditContractId = ref('')
  const contractEditRef = ref()

  // 格式化金额
  const formatAmount = (amount: number | string | undefined) => {
    if (amount === undefined || amount === null) return '0.00'
    return parseFloat(amount.toString()).toFixed(2)
  }

  // 计算剩余天数
  const calculateDaysLeft = (endTime: number | string | undefined) => {
    if (!endTime || endTime === 0) return 0
    const ts = typeof endTime === 'string' ? parseInt(endTime) : endTime

    if (isNaN(ts) || ts <= 0) {
      return 0
    }

    // 获取当前时间戳（秒级）
    const now = Math.floor(Date.now() / 1000)

    // 计算剩余天数
    const diffTime = ts - now
    const diffDays = Math.ceil(diffTime / (24 * 60 * 60))

    return diffDays
  }

  // 基础搜索
  const handleSearch = () => {
    queryForm.page = 1
    loadContractList()
  }

  // 重置搜索
  const handleReset = () => {
    // 重置基础搜索表单
    queryForm.keywords = ''
    queryForm.cate_id = ''
    queryForm.sign_name = ''
    queryForm.page = 1
    signUserOptions.value = []
    
    // 重置高级搜索表单
    resetAdvancedSearch()
    
    loadContractList()
  }

  // 切换高级搜索面板
  const toggleAdvancedSearch = () => {
    isAdvancedSearch.value = !isAdvancedSearch.value
  }

  // 关闭高级搜索面板
  const closeAdvancedSearch = () => {
    isAdvancedSearch.value = false
  }

  // 高级搜索
  const handleAdvancedSearch = () => {
    queryForm.page = 1
    loadContractList()
  }

  // 重置高级搜索条件
  const resetAdvancedSearch = () => {
    advancedForm.signTimeRange = []
    advancedForm.min_amount = null
    advancedForm.max_amount = null
    advancedForm.min_cost2 = null
    advancedForm.max_cost2 = null
    advancedForm.is_cleared = null
    advancedForm.has_cost3 = null
    advancedForm.is_expired = null
  }

  // 搜索签约人
  const searchSignUsers = async (keywords: string) => {
    if (!keywords) {
      signUserOptions.value = []
      return
    }

    signUserLoading.value = true
    try {
      const res: ApiResponse<any[]> = await request({
        url: '/api/contract/contract/get_sign_users',
        method: 'get',
        params: {
          keywords: keywords,
          limit: 20,
        },
      })

      if (res.code === 0) {
        signUserOptions.value = res.data || []
      } else {
        ElMessage.error(res.msg || '获取签约人列表失败')
      }
    } catch (error) {
      ElMessage.error('获取签约人列表失败')
    } finally {
      signUserLoading.value = false
    }
  }

  // 加载合同列表
  const loadContractList = async () => {
    try {
      loading.value = true

      // 构造查询参数
      const params: any = {
        ...queryForm,
        min_amount: advancedForm.min_amount,
        max_amount: advancedForm.max_amount,
        min_cost2: advancedForm.min_cost2,
        max_cost2: advancedForm.max_cost2,
      }

      // 确保分页参数是正确的数字类型
      params.page = parseInt(params.page.toString()) || 1
      params.limit = parseInt(params.limit.toString()) || 10

      // 处理时间范围参数
      if (advancedForm.signTimeRange && advancedForm.signTimeRange.length === 2) {
        params.sign_start_time = advancedForm.signTimeRange[0]
        params.sign_end_time = advancedForm.signTimeRange[1]
      }

      // 处理款项结清和后期费用筛选
      if (advancedForm.is_cleared !== null && advancedForm.is_cleared !== undefined) {
        params.is_cleared = advancedForm.is_cleared
      }

      if (advancedForm.has_cost3 !== null && advancedForm.has_cost3 !== undefined) {
        params.has_cost3 = advancedForm.has_cost3
      }

      // 处理是否到期筛选
      if (advancedForm.is_expired !== null && advancedForm.is_expired !== undefined) {
        params.is_expired = advancedForm.is_expired
      }

      // 调试日志：查看传递的参数
      console.log('传递的高级搜索参数:', params)
      console.log('高级搜索表单数据:', advancedForm)

      // 确定API端点
      const apiEndpoint = '/api/contract/contract/list'

      // 直接调用API接口而不是使用store
      const res: ApiResponse<{
        list: ContractItem[]
        limit?: number
        page?: number
        pages?: number
        total?: number
      }> & { count?: number } = await request({
        url: apiEndpoint,
        method: 'get',
        params,
      })

      // 添加日志查看原始数据结构
      if (res.code === 0) {
        // 正确解析后端返回的分页数据结构
        const list = res.data.list || []
        // 优先使用data.total，如果不存在则尝试使用外部count字段
        const totalCount = res.data.total || res.count || 0

        // 处理时间字段和计算剩余天数
        contractList.value = list.map((item: any) => {
          // 格式化时间字段（使用统一的工具函数）
          if (item.sign_time) {
            item.sign_time_formatted = formatDate(item.sign_time, 'YYYY-MM-DD')
          }

          if (item.end_time) {
            item.end_time_formatted = formatDate(item.end_time, 'YYYY-MM-DD')
            // 计算剩余天数
            item.delay = calculateDaysLeft(item.end_time)
          }

          // 添加款项结清标志
          item.is_cleared = parseFloat(item.cost) === parseFloat(item.cost2)

          // 添加是否有后期费用标志
          item.has_cost3 = item.cost3 && item.cost3.trim() !== ''

          // 签约人处理：通过sign_uid从管理员用户列表中查找用户名
          if (item.sign_uid) {
            if (adminUsers.value.length > 0) {
              const user = adminUsers.value.find(u => Number(u.id) === Number(item.sign_uid))
              if (user) {
                item.sign_name = user.name
              } else {
                item.sign_name = `用户ID:${item.sign_uid}`
              }
            } else {
              // 如果管理员用户列表还未加载，暂时显示用户ID
              item.sign_name = `用户ID:${item.sign_uid}`
            }
          }

          // 合同类别处理：通过cate_id从合同分类列表中查找类别名称
          if (item.cate_id && contractCategories.value.length > 0) {
            const category = contractCategories.value.find(
              cate => Number(cate.id) === Number(item.cate_id)
            )
            if (category) {
              item.cate_name = category.title || category.name || '未知类别'
            } else {
              item.cate_name = '未分类'
            }
          } else if (!item.cate_name) {
            item.cate_name = '未分类'
          }

          return item
        })

        // 正确设置总数，确保分页组件能正确显示页数
        total.value = totalCount
      } else {
        ElMessage.error(res.msg || '获取合同列表失败')
      }
    } catch (error) {
      ElMessage.error('获取合同列表失败')
    } finally {
      loading.value = false
    }
  }

  // 查看合同详情
  const handleView = (row: ContractItem) => {
    // 先关闭再打开抽屉，确保每次点击都会触发重新加载
    detailDrawerVisible.value = false
    // 使用setTimeout确保关闭动画完成后再打开
    setTimeout(() => {
      currentDetailContractId.value = row.id.toString()
      detailDrawerVisible.value = true
    }, 300)
  }

  // 新增合同
  const handleAdd = () => {
    addDrawerVisible.value = true
    // 使用nextTick确保抽屉DOM渲染后再重置表单
    nextTick(() => {
      if (contractAddRef.value) {
        contractAddRef.value.resetForm()
      }
    })
  }

  // 关闭新增抽屉
  const closeAddDrawer = () => {
    addDrawerVisible.value = false
    // 关闭抽屉后也重置表单，保证下次打开是干净的
    if (contractAddRef.value) {
      contractAddRef.value.resetForm()
    }
  }

  // 处理新增提交
  const handleAddSubmit = () => {
    closeAddDrawer()
    loadContractList()
  }

  // 确认新增
  const handleConfirmAdd = () => {
    if (contractAddRef.value) {
      contractAddRef.value.submitForm()
    }
  }

  // 提交编辑表单
  const submitEditForm = () => {
    if (contractEditRef.value) {
      contractEditRef.value.submitForm()
    }
  }

  // 处理编辑抽屉打开
  const handleEditDrawerOpen = () => {
    // 编辑模式下不需要在这里重置表单
    // 因为SaleContractEdit组件会根据contractId直接加载对应数据
    // 保留此方法以防将来需要添加其他打开时的逻辑
  }

  // 编辑合同
  const handleEdit = (row: ContractItem) => {
    // 先关闭再打开抽屉，确保每次点击都会触发重新加载
    editDrawerVisible.value = false
    // 使用setTimeout确保关闭动画完成后再打开
    setTimeout(() => {
      currentEditContractId.value = row.id.toString()
      editDrawerVisible.value = true
    }, 300)
  }

  // 关闭编辑抽屉
  const closeEditDrawer = () => {
    editDrawerVisible.value = false
  }

  // 处理编辑提交
  const handleEditSubmit = () => {
    ElMessage.success('合同编辑成功')
    closeEditDrawer()
    loadContractList()
  }

  // 处理命令操作
  const handleCommand = async (command: any) => {
    const { action, row } = command

    // 如果是编辑操作，直接打开编辑抽屉，不进行路由导航
    if (action === 'edit') {
      handleEdit(row)
      return
    }

    // 处理合同中止操作
    if (action === 'stop') {
      handleStopContract(row)
      return
    }

    // 处理合同作废操作
    if (action === 'void') {
      handleVoidContract(row)
      return
    }
  }

  // 分页相关
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    queryForm.page = 1 // 切换每页条数时返回第一页
    loadContractList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    loadContractList()
  }

  // 处理合同中止操作
  const handleStopContract = async (row: ContractItem) => {
    try {
      // 提示用户输入中止备注
      const { value: remark } = await ElMessageBox.prompt(
        `确定要中止合同"${row.name}"吗？中止后合同将无法继续执行。\n\n请输入中止备注：`,
        '确认中止合同',
        {
          confirmButtonText: '确定中止',
          cancelButtonText: '取消',
          type: 'warning',
          inputPattern: /.+/,
          inputErrorMessage: '中止备注不能为空',
        }
      )

      if (!remark) return

      const response: ApiResponse<any> = await contractApi.contractStop({
        id: row.id,
        stop_remark: remark,
      })

      if (response.code === 0) {
        ElMessage.success('合同中止成功')
        // 刷新列表数据
        loadContractList()
      } else {
        ElMessage.error(response.msg || '合同中止失败')
      }
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('中止合同错误:', error)
        ElMessage.error('合同中止失败')
      }
    }
  }

  // 处理合同作废操作
  const handleVoidContract = async (row: ContractItem) => {
    try {
      // 提示用户输入作废备注
      const { value: remark } = await ElMessageBox.prompt(
        `确定要作废合同"${row.name}"吗？作废后合同将永久无效，请谨慎操作。\n\n请输入作废备注：`,
        '确认作废合同',
        {
          confirmButtonText: '确定作废',
          cancelButtonText: '取消',
          type: 'warning',
          inputPattern: /.+/,
          inputErrorMessage: '作废备注不能为空',
        }
      )

      if (!remark) return

      const response: ApiResponse<any> = await contractApi.contractVoid({
        id: row.id,
        void_remark: remark,
      })

      if (response.code === 0) {
        ElMessage.success('合同作废成功')
        // 刷新列表数据
        loadContractList()
      } else {
        ElMessage.error(response.msg || '合同作废失败')
      }
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('作废合同错误:', error)
        ElMessage.error('合同作废失败')
      }
    }
  }

  // 添加获取合同分类的方法
  const getContractCategories = async () => {
    try {
      // 首先尝试从缓存中获取
      const cachedData = localStorage.getItem(CONTRACT_CATEGORIES_CACHE_KEY)
      if (cachedData) {
        const parsedData = JSON.parse(cachedData)
        // 检查缓存时间是否超过24小时
        if (
          parsedData.timestamp &&
          new Date().getTime() - parsedData.timestamp < 24 * 60 * 60 * 1000
        ) {
          contractCategories.value = parsedData.data
          return
        }
      }

      // 缓存过期或不存在，从服务器获取
      const response: ApiResponse<any[]> = await request({
        url: '/api/contract/cate/set',
        method: 'get',
      })

      if (response.code === 0 && response.data) {
        contractCategories.value = response.data

        // 将数据存入缓存，并记录时间戳
        localStorage.setItem(
          CONTRACT_CATEGORIES_CACHE_KEY,
          JSON.stringify({
            data: response.data,
            timestamp: new Date().getTime(),
          })
        )
      } else {
        ElMessage.error(response.msg || '获取合同分类失败')
      }
    } catch (error) {
      ElMessage.error('获取合同分类失败')
    }
  }

  // 添加获取管理员用户列表的方法
  const getAdminUsers = async () => {
    try {
      // 首先尝试从缓存中获取
      const cachedData = localStorage.getItem(ADMIN_USERS_CACHE_KEY)
      if (cachedData) {
        const parsedData = JSON.parse(cachedData)
        // 检查缓存时间是否超过24小时
        if (
          parsedData.timestamp &&
          new Date().getTime() - parsedData.timestamp < 24 * 60 * 60 * 1000
        ) {
          adminUsers.value = parsedData.data
          return
        }
      }

      // 缓存过期或不存在，从服务器获取
      const response: ApiResponse<AdminUser[]> = await request({
        url: '/api/contract/contract/get_sign_users',
        method: 'get',
        params: {
          limit: 1000, // 获取足够多的用户
        },
      })

      if (response.code === 0 && response.data) {
        adminUsers.value = response.data

        // 将数据存入缓存，并记录时间戳
        localStorage.setItem(
          ADMIN_USERS_CACHE_KEY,
          JSON.stringify({
            data: response.data,
            timestamp: new Date().getTime(),
          })
        )
      } else {
        ElMessage.error(response.msg || '获取管理员用户列表失败')
      }
    } catch (error) {
      ElMessage.error('获取管理员用户列表失败')
    }
  }

  // 初始化加载
  onMounted(() => {
    getContractCategories()
    getAdminUsers()
    loadContractList()
  })
</script>

<style scoped>
  .contract-container {
    padding: 20px;
    position: relative;
  }

  .contract-header {
    margin-bottom: 20px;
    position: relative;
    z-index: 9;
  }

  .basic-search-form {
    border-bottom: 1px solid transparent;
    transition: all 0.2s;
  }

  .contract-content {
    margin-top: 20px;
    margin-bottom: 20px;
    position: relative;
    z-index: 5;
  }

  /* 高级搜索面板样式 */
  .advanced-search-panel {
    width: 100%;
    background-color: #f5f7fa;
    border-radius: 0 0 4px 4px;
    padding: 20px;
    border: 1px solid #e4e7ed;
    border-top: none;
    margin-top: -1px;
    position: relative;
    z-index: 8;
    overflow: visible;
    min-height: 200px;
  }

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 1px solid #dcdfe6;
  }

  .panel-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 15px;
    font-weight: bold;
    color: #303133;
  }

  /* 搜索按钮布局 */
  .search-buttons {
    display: flex;
    justify-content: space-between;
    width: 100%;
    align-items: center;
  }

  .left-buttons {
    display: flex;
    gap: 10px;
  }

  .right-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  /* 高级搜索按钮布局 */
  .advanced-buttons {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    width: 100%;
  }

  .table-toolbar {
    margin-bottom: 15px;
    display: flex;
    gap: 10px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  /* 表格状态样式 */
  :deep(.el-tag--success) {
    background-color: #f0f9eb;
    border-color: #e1f3d8;
    color: #67c23a;
  }

  :deep(.el-tag--danger) {
    background-color: #fef0f0;
    border-color: #fde2e2;
    color: #f56c6c;
  }

  /* 按钮间距 */
  .el-button + .el-dropdown {
    margin-left: 5px;
  }

  /* 金额单元格样式 */
  .amount-cell {
    font-family: 'Courier New', monospace;
    font-weight: 500;
    color: #606266;
  }

  /* 剩余天数样式 */
  .delay-normal {
    color: #67c23a;
    font-weight: bold;
  }

  .delay-expired {
    color: #f56c6c;
    font-weight: bold;
  }

  /* 金额输入容器 */
  .amount-input-container {
    display: flex;
    align-items: center;
    width: 100%;
    flex-wrap: nowrap;
  }

  .mx-2 {
    width: 30px;
    text-align: center;
    flex-shrink: 0;
  }

  @media screen and (max-width: 992px) {
    .amount-input-container {
      flex-direction: row;
      gap: 5px;
    }
  }

  @media screen and (max-width: 480px) {
    .amount-input-container {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }

    .mx-2 {
      width: 100%;
      margin: 5px 0;
      text-align: center;
    }
  }

  /* 高级搜索表单样式 */
  :deep(.advanced-search-form) {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 15px;
    width: 100%;
  }

  :deep(.advanced-search-form .form-item) {
    margin: 0;
    width: 100%;
  }

  :deep(.advanced-search-form .el-form-item__content) {
    width: 100%;
  }

  /* 特殊处理合同金额表单项 */
  :deep(.advanced-search-form .form-item[data-field='amount']),
  :deep(.advanced-search-form .form-item[data-field='cost2']) {
    grid-column: span 2;
  }

  /* 操作按钮样式 */
  :deep(.advanced-search-form .action-buttons) {
    grid-column: 1 / -1;
    margin: 10px 0 0 0;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.advanced-search-form .action-buttons .el-form-item__content) {
    display: flex;
    justify-content: flex-end;
  }

  /* 抽屉内容样式 */
  .drawer-content {
    padding: 15px;
    overflow-y: auto;
  }

  /* 表格中的操作按钮样式统一 */
  :deep(.operation-buttons) {
    display: flex;
    gap: 8px;
  }

  /* 状态标签统一样式 */
  :deep(.el-tag) {
    padding: 2px 8px;
    border-radius: 4px;
  }

  /* 表单标签样式 */
  :deep(.el-form-item__label) {
    white-space: nowrap;
    padding-right: 12px;
  }

  :deep(.el-form-item) {
    margin-bottom: 18px;
  }

  :deep(.advanced-search-form .el-form-item) {
    margin-right: 15px;
  }

  /* 高级搜索面板响应式布局 */
  @media screen and (max-width: 1400px) {
    :deep(.advanced-search-form) {
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    }
  }

  @media screen and (max-width: 1200px) {
    :deep(.advanced-search-form) {
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    }

    :deep(.advanced-search-form .form-item[data-field='amount']),
    :deep(.advanced-search-form .form-item[data-field='cost2']) {
      grid-column: 1 / -1;
    }
  }

  @media screen and (max-width: 992px) {
    :deep(.advanced-search-form) {
      grid-template-columns: 1fr 1fr;
    }

    :deep(.advanced-search-form .form-item[data-field='amount']),
    :deep(.advanced-search-form .form-item[data-field='cost2']) {
      grid-column: span 2;
    }

    :deep(.el-form-item__label) {
      width: 90px !important;
    }

    :deep(.el-form-item__content) {
      margin-left: 90px !important;
    }
  }

  @media screen and (max-width: 768px) {
    :deep(.advanced-search-form) {
      grid-template-columns: 1fr;
    }

    :deep(.advanced-search-form .form-item) {
      grid-column: 1 / -1;
    }

    .advanced-search-panel {
      padding: 15px 10px;
    }

    :deep(.el-form-item__label) {
      width: 80px !important;
      padding-right: 5px;
      font-size: 14px;
    }

    :deep(.el-form-item__content) {
      margin-left: 80px !important;
    }

    :deep(.advanced-search-form .action-buttons .el-form-item__content) {
      margin-left: 0 !important;
    }
  }
</style>